package drds.binlog.database_driver.packets.client;

import drds.binlog.common.Authors;
import drds.binlog.database_driver.packets.CommandPacket;
import drds.binlog.database_driver.packets.IGtidSet;
import drds.binlog.database_driver.utils.Bytes;
import drds.common.Author;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * https://dev.mysql.com/doc/internals/en/com-binlog-dump-gtid.html
 */
@Author(name = Authors.LI_YANG)
public class BinlogDumpGtidCommandPacket extends CommandPacket
{

    public static final int BINLOG_DUMP_NON_BLOCK = 0x01;
    public static final int BINLOG_THROUGH_POSITION = 0x02;
    public static final int BINLOG_THROUGH_GTID = 0x04;

    @Setter
    @Getter
    public long slaveServerId;
    @Setter
    @Getter
    public IGtidSet gtidSet;

    public BinlogDumpGtidCommandPacket()
    {
        setCommand((byte) 0x1e);
    }

    @Override
    public void fromBytes(byte[] bytes) throws IOException
    {
    }

    @Override
    public byte[] toBytes() throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        // 0. [1] write command number
        byteArrayOutputStream.write(getCommand());
        // 1. [2] flags
        Bytes.writeUnsigned2IntLittleEndian(byteArrayOutputStream, BINLOG_THROUGH_GTID);
        // 2. [4] server-id
        Bytes.writeUnsigned4IntLittleEndian(byteArrayOutputStream, slaveServerId);
        // 3. [4] binlog-filename-len
        Bytes.writeUnsigned4IntLittleEndian(byteArrayOutputStream, 0);
        // 4. [] binlog-filename
        // skip
        // 5. [8] binlog-pos
        Bytes.writeUnsigned8IntLittleEndian(byteArrayOutputStream, 4);
        // if flags & BINLOG_THROUGH_GTID {
        byte[] bytes = gtidSet.encode();
        // 6. [4] data-size
        Bytes.writeUnsigned4IntLittleEndian(byteArrayOutputStream, bytes.length);
        // 7, [] data
        // [8] n_sids // 文档写的是4个字节，其实是8个字节
        // for n_sids {
        // [16] SID
        // [8] n_intervals
        // for n_intervals {
        // [8] start (signed)
        // [8] end (signed)
        // }
        // }
        byteArrayOutputStream.write(bytes);
        // }

        return byteArrayOutputStream.toByteArray();
    }
}
